package com.example.agriapp.view.activity;

import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.agriapp.model.ProductContract;
import com.example.agriapp.R;
import com.example.agriapp.model.bean.Product;
import com.example.agriapp.adapter.LiuLanAdapter;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private RecyclerView recyclerView;
    private EditText searchView;
    private TextView tvFind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_search);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_nav_icon_selected));

        tabLayout = findViewById(R.id.tabLayout);
        tvFind = findViewById(R.id.tvFind);
        tabLayout.addTab(tabLayout.newTab().setText("售卖信息"));
        tabLayout.addTab(tabLayout.newTab().setText("采购信息"));
        tabLayout.addTab(tabLayout.newTab().setText("店铺"));
        searchView = findViewById(R.id.search_view);
        setupTabAppearance(tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 更新选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(true);
                }

                // 根据选中的Tab加载数据
                switch (tab.getPosition()) {
                    case 0:
                        // presenter.loadProducts();
                        break;
                    case 1:
                        //presenter.loadProductsByCategory("水果蔬菜");
                        break;
                    case 2:
                        // presenter.loadProductsByCategory("米面粮油");
                        break;

                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 更新未选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // Tab被重新选中时的处理（可选）
            }
        });

        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        tvFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = searchView.getText().toString().trim();
                if (trim.isEmpty()) {
                    Toast.makeText(SearchActivity.this, "请输入查询内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<Product> productList = getProductsByCategory(trim);
                Log.e("TAG", "onClick: "+productList.size()+"        "+trim );
                // 设置适配器
                LiuLanAdapter adapter = new LiuLanAdapter(SearchActivity.this, productList);
                recyclerView.setAdapter(adapter);
            }
        });
    }

    private void setupTabAppearance(TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                TextView tabView = new TextView(this);
                tabView.setText(tab.getText());
                tabView.setGravity(Gravity.CENTER);
                tab.setCustomView(tabView);
            }
        }

        // 默认选中第一个Tab
        TabLayout.Tab firstTab = tabLayout.getTabAt(0);
        if (firstTab != null && firstTab.getCustomView() != null) {
            firstTab.getCustomView().setSelected(true);
        }
    }

    private List<Product> getProductsByCategory(String category) {
        List<Product> products = new ArrayList<>();
        Cursor cursor = this.getContentResolver().query(
                ProductContract.ProductEntry.CONTENT_URI,
                null,
                ProductContract.ProductEntry.COLUMN_CATEGORY + " = ?",
                new String[]{category},
                null
        );

        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = new Product();
                    product.setId(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_ID)));
                    product.setTitle(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_TITLE)));
                    product.setPrice(cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRICE)));
                    product.setQuantity(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_QUANTITY)));
                    product.setCategory(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_CATEGORY)));
                    product.setImage(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_IMAGE)));

                    products.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        return products;
    }
}